package vip.xiaonuo.modular.task;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import vip.xiaonuo.modular.constant.CommonConstant;
import vip.xiaonuo.modular.entity.BasGpsExec;
import vip.xiaonuo.modular.entity.BasGpsSuccess;
import vip.xiaonuo.modular.entity.GpsInfo;
import vip.xiaonuo.modular.entity.Shipment;
import vip.xiaonuo.modular.entity.dto.GPSInfoDTO;
import vip.xiaonuo.modular.entity.request.InsertLocusInfoRequest;
import vip.xiaonuo.modular.entity.request.QueryGPSInfoRequest;
import vip.xiaonuo.modular.service.*;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author tuchaoren
 * @Date 2021-06-30
 **/
@Component
@Slf4j
public class GPSInfoPushTask {

    @Autowired
    private WaybillService waybillService;
    @Autowired
    private LocusResultService locusResultService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private BasGpsExecService basGpsExecService;
    @Autowired
    private BasGpsSuccessService basGpsSuccessService;

    @Autowired
    private GpsInfoService gpsInfoService;
    @Autowired
    private ShipmentService shipmentService;
    private final String ORDER_STATUS_COMPLETE = "90";

    @Scheduled(cron = "0 0/1 * * * ?")
    public void infoPush() {
        log.info("==========================================定时任务开始==============================================");
        waybillService.queryWaybill();
    }

    @Scheduled(cron = "0 0/2 * * * ?")
    public synchronized void gpsGet() {
        String truckListStr = stringRedisTemplate.opsForValue().get(CommonConstant.ACTIVATION_TRUCK);
        if(StringUtils.isBlank(truckListStr)){
            return;
        }
        List<String> truckList = JSONUtil.toList(truckListStr, String.class);
        String gpsDatePrev = String.valueOf(System.currentTimeMillis() - 60000);
        String gpsDateNext = System.currentTimeMillis() + "";
        for(String truck: truckList){
            try{
                QueryGPSInfoRequest gpsInfoRequest = new QueryGPSInfoRequest();
                gpsInfoRequest.setTruckId(truck);
                gpsInfoRequest.setStartTime(gpsDatePrev);
                gpsInfoRequest.setEndTime(gpsDateNext);
                List<BasGpsExec> basGpsExecList = gpsInfoService.getInterfaceGPS(gpsInfoRequest);
                if(basGpsExecList.size() > 0){
                    basGpsExecList.forEach(data -> {
                        data.setId(null);
                    });
                    basGpsExecService.save(basGpsExecList.get(basGpsExecList.size() - 1));
                }
                log.info(JSONUtil.toJsonStr(basGpsExecList));
            }catch (Exception e){
                log.error("车牌："+truck+"获取异常");
                e.printStackTrace();
            }
        }
//        stringRedisTemplate.opsForValue().set(CommonConstant.GPS_DATE_PREV, gpsDateNext);

    }
    @Scheduled(cron = "30 * * * * ?")
    public synchronized void gpsPush() {
        IPage<BasGpsExec> p = basGpsExecService.page(new Page<BasGpsExec>(1, 500), new QueryWrapper<BasGpsExec>().orderByAsc("date_time"));
        Map<String, List<BasGpsExec>> truckMap = new HashMap<String, List<BasGpsExec>>();

        List<String> ids = new ArrayList<String>();
        for(BasGpsExec exec: p.getRecords()){
            List<BasGpsExec> basGpsExecList = truckMap.get(exec.getTruckId());
            if(basGpsExecList == null){
                basGpsExecList = new ArrayList<BasGpsExec>();
                truckMap.put(exec.getTruckId(), basGpsExecList);
            }
            basGpsExecList.add(exec);
            ids.add(exec.getId());
        }
        for(String truck: truckMap.keySet()){
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("vehicle_no", truck);
            queryWrapper.ne("status", "90");
            List<Shipment> shipmentList = shipmentService.getBaseMapper().selectList(queryWrapper);
            List<BasGpsExec> basGpsExecList = truckMap.get(truck);
            for(Shipment shipment: shipmentList){
                InsertLocusInfoRequest locusInfo = new InsertLocusInfoRequest();
                locusInfo.setVehicle_no(truck);
                locusInfo.setShipment_no(shipment.getShipmentNo());
                List<GPSInfoDTO> gpsInfoDTOS = new ArrayList<>();
                basGpsExecList.forEach(gpsData -> {
                    GPSInfoDTO gpsInfoDTO = new GPSInfoDTO();
                    gpsInfoDTO.setLongitude(gpsData.getLongitude());
                    gpsInfoDTO.setLatitude(gpsData.getLatitude());
                    gpsInfoDTO.setSpeed(new BigDecimal(0));
                    gpsInfoDTO.setDate(gpsData.getDateTime());
                    gpsInfoDTOS.add(gpsInfoDTO);
                });
                locusInfo.setGps(gpsInfoDTOS);
                if(gpsInfoDTOS.size() > 0){
                    locusResultService.insertLocusInfo(locusInfo);
                }

                // 异步新增获取的gps信息
                List<GpsInfo> list = new ArrayList<>();
                if(basGpsExecList.size() > 0){
                    basGpsExecList.forEach(data -> {
                        GpsInfo gpsInfo = new GpsInfo();
                        gpsInfo.setShipmentNo(shipment.getShipmentNo());
                        gpsInfo.setDate(DateUtil.parse(data.getDateTime(), "yyyy-MM-dd HH:mm:ss"));
                        gpsInfo.setVehicleNo(shipment.getVehicleNo());
                        gpsInfo.setLatitude(data.getLatitude());
                        gpsInfo.setLongitude(data.getLongitude());
                        gpsInfo.setVehicleNo(data.getTruckId());
                        gpsInfo.setSpeed(new BigDecimal(0));
                        gpsInfo.setSouceId(data.getId());
                        gpsInfo.setCreateTime(new Date());
                        list.add(gpsInfo);
                    });
                    gpsInfoService.batchInsertGpsInfo(list);

                }

            }
        }
        if(p.getRecords().size() > 0){
            List<BasGpsSuccess> basGpsSuccessesList = new ArrayList<>();
            p.getRecords().forEach(data -> {
                BasGpsSuccess basGpsSuccess = new BasGpsSuccess();
                BeanUtils.copyProperties(data, basGpsSuccess);
                basGpsSuccessesList.add(basGpsSuccess);

            });
            basGpsSuccessService.saveBatch(basGpsSuccessesList);
            basGpsExecService.removeByIds(ids);
        }

    }



}
